
import React,{Component}from 'react';
import { View,Text,TextInput, Image,ImageBackground,StyleSheet, TouchableOpacity} from "react-native";
import { px2dp, px2sp } from '../utils/DisplayUtils';
import UserManager from '../common/UserManager';
import Utils from '../utils/Utils';
import TabPage from './TabPage'
import ToastUtils from "../components/ToastUtils";
import {Toast, InputItem, Modal as AntdModal, portal} from '@ant-design/react-native';
import {getAppVersionConfigApi} from '../api/AppApi'
import {userLogin, generateLongTokenApi, validateLongTokenApi} from "../api/LoginApi"

import UpdateVersionView from '../components/UpdateVersionView/UpdateVersionView'
import Constants from '../common/Constants';

import {XUpdate, InitArgs, UpdateArgs} from 'react-native-xupdate-new';



export default class LoginPage extends Component{

    constructor(props) {
        super(props);
        this.state = {
          username: '',
          password: '',
          updateMsg:'',
          isForce: false,
          isShowUpdate: false,
          updateUrl:'',
          sVisible: true,
          ipAddress:'',
          port:'',
          loading: null,
          currentVersion: 999
        };


       
        
        
       
      }

      componentDidMount(){
        this.initXUpdate();
        this.getDefaultData()

        // this.getVersionInfo()

        // this.getVersionInfo();
      }

      componentWillUnmount() {
        XUpdate.removeErrorListener(this.errorListener);
      }

      getVersionInfo(){

        getAppVersionConfigApi().then(async (resp) => {
    
          console.log( 'getAppVersionConfigApi:', resp)
          if(resp.versionCode){

            this.checkUpdateDefault(resp)
            // var apkUrl = Constants.downUrl + '/RF_Attachment/AppMenuAttachment/' + resp.name
            // var apkUrl = 'https://cos.pgyer.com/c4f8d60d6d45f9edb5c071881f73e5d7.apk?sign=6b5f0d1e299979c999947d2b24a4395e&t=1646712671&response-content-disposition=attachment%3Bfilename%3D%E6%97%A5%E4%B8%B0%E5%85%A8%E6%99%AF_1.4.1.apk'
            // this.setState({isShowUpdate: true, updateMsg: resp.distributeDesc, isForce: (resp.isForce == 'Y' ? true : false), updateUrl: apkUrl})
            
          }
         
      }).catch((error)=>{
        // ToastUtils.showToast( error);
        console.log("error is:", error)
        Toast.info(error)
      });

      }

/**
 * 
 {
  "Code": 0, //0代表请求成功，非0代表失败
  "Msg": "", //请求出错的信息
  "UpdateStatus": 1, //0代表不更新，1代表有版本更新，不需要强制升级，2代表有版本更新，需要强制升级
  "VersionCode": 3, //编译版本号(唯一)
  "VersionName": "1.0.2", //版本名(用于展示)
  "ModifyContent": "1、优化api接口。\r\n2、添加使用demo演示。\r\n3、新增自定义更新服务API接口。\r\n4、优化更新提示界面。", //更新内容
  "DownloadUrl": "https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk",// 文件下载地址
  "ApkSize": 2048, //文件的大小(单位:kb)
  "ApkMd5": "..."  //md5值没有的话，就无法保证apk是否完整，每次都会重新下载。框架默认使用的是md5加密。
}
 */
      ///初始化
initXUpdate() {
  ///设置初始化参数
  let args = new InitArgs();
  ///是否输出日志
  args.debug = true;
  ///post请求是否是上传json
  args.isPostJson = false;
  ///是否只在wifi下才能进行更新
  args.isWifiOnly = false;
  ///是否开启自动模式
  args.isAutoMode = false;
  ///是否支持静默安装，这个需要设备有root权限
  args.supportSilentInstall = false;
  ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
  args.enableRetry = false;

  ///初始化SDK
  XUpdate.init(args).then(result => {

    console.log('初始化成功:');
    this.setState({currentVersion: result.versionCode})

    console.log(JSON.stringify(result));
      // this.setState({
      //     _message: '初始化成功:' + JSON.stringify(result),
      // });
  }).catch(error => {
      console.log(error);
      // this.setState({
      //     _message: '初始化失败:' + error,
      // });
  });

  //设置自定义解析
  // XUpdate.setCustomParser({parseJson: this.customParser});
  //设置错误监听
  XUpdate.addErrorListener(this.errorListener);
}

 //自定义的异常处理
 errorListener = (error) => {
  console.log('error:' +  JSON.stringify(error));


  if(error.code === 2004){

  }else{
    Toast.info(error.detailMsg)
  }

 
  // //下载失败
  // if (error.code === 4000) {
  //   XUpdate.showRetryUpdateTip(
  //     'Github被墙无法继续下载，是否考虑切换蒲公英下载？',
  //     'https://www.pgyer.com/flutter_learn',
  //   );
  // }
  // this.setState({
  //   _message: '发送异常：' + JSON.stringify(error),
  // });
};




checkUpdateDefault(resp) {

  console.log("resp is:" +  JSON.stringify(resp))

   // var apkUrl = Constants.downUrl + '/RF_Attachment/AppMenuAttachment/' + resp.name
   var apkUrl = 'https://cos.pgyer.com/c4f8d60d6d45f9edb5c071881f73e5d7.apk?sign=6b5f0d1e299979c999947d2b24a4395e&t=1646712671&response-content-disposition=attachment%3Bfilename%3D%E6%97%A5%E4%B8%B0%E5%85%A8%E6%99%AF_1.4.1.apk'
   // this.setState({isShowUpdate: true, updateMsg: resp.distributeDesc, isForce: (resp.isForce == 'Y' ? true : false), updateUrl: apkUrl})
   

  let downloadurl =   Constants.downUrl + '/RF_Attachment/AppMenuAttachment/' + resp.name
  var _updateUrl = Constants.serverUrl + '/RF_Attachment/AppMenuAttachment/config.json'

  let args = new UpdateArgs(_updateUrl);
  args.supportBackgroundUpdate = true;
  args.themeColor = '#FF0081cc';
  let hasUpdate = this.state.currentVersion < resp.versionCode * 1 ? true : false
  // args.topImageRes='bg_updage_top'

  // args.isCustomParse = true;
  // XUpdate.update(args);
  XUpdate.updateByInfo(args,{
    hasUpdate: hasUpdate,
    versionCode: resp.versionCode * 1,
    versionName: resp.version,
    updateContent: resp.distributeDesc,
    downloadUrl:  downloadurl,
    isIgnorable:false,
    isForce: (resp.isForce == 'Y' ? true : false)
    //选填
    // isIgnorable: AppInfo['isIgnorable'],
    // apkSize: AppInfo['apkSize'],
})
}

      async getDefaultData(){

        this.setState({ sVisible: false})
        const that = this

        let user = await UserManager.getUserInfo()
        var ipAddress = await UserManager.getIpAddress()
        var port = await UserManager.getPort()
        var userName = ''
        console.log("ipAddress:"+ ipAddress)
        console.log("port:" + port)

        if(ipAddress != '' && ipAddress != null && port != null && port != ''){
          Constants.serverPort = port
          Constants.serverUrl = ipAddress
        }else{
          ipAddress = Constants.serverUrl
          port = Constants.serverPort + ''
        }

        if(user != null){

          userName = user.UserName
        }


        this.setState({username: userName, ipAddress: ipAddress, port: port})
        
      }

     login() {

      // Toast.loading('loading') 
        let username = '';
        if (Utils.isEmpty(this.state.username)) {
          username = '';
        } else {
          username = this.state.username;
        }
        let password = this.state.password;
        if (Utils.isEmpty(username) || Utils.isEmpty(password)) {
          Toast.info('用户名或密码不能为空');
          // ToastUtils.showToast('用户名或密码不能为空');
          return;
        }

      const contextParam = {
      };
      const parameters = [{
          "Value": username,
      }, {
          "Value": password,
      }];
     
      const params = {
          ApiType: "AppSecurtiyController",
          Context: contextParam,
          Method:"Login",
          Parameters: parameters

      };
     const loading = Toast.loading('loading',0)
     this.setState({loading: loading})
        userLogin(params).then( async (resp) => {
    
          const that = this
          // Toast.showToast(resp.Context.Ticket);
          // const token = `Bearer ${resp.token}`;
          // global.jwtToken = resp.Context.Ticket;
          // global.userInfo = resp.result;
          // this.props.navigation.replace("TabPage");
          if(resp.Success){
            console.log( 'userLogin', resp.Context.Ticket)
          await  UserManager.setUserInfo(resp.Result )
          await  UserManager.setTicket(resp.Context.Ticket)
           that.getLongTicket()
            

          }
          // getLongToken();
      }, (err)=>{
        // console.log("err is :"  + err)
        Toast.info(err)
        this.closeLoading()
        
      }).catch((error)=>{
        // ToastUtils.showToast( error);
        console.log(error)
        Toast.info(error)
        this.closeLoading()
      });
      }

    closeLoading(){
      if(this.state.loading != null){
        Toast.remove(this.state.loading)
          this.setState({loading: null})
      }
    }



    getLongTicket(){

      const that = this

      generateLongTokenApi().then(async (res)=>{

        //{"Context": {"InvOrgId": 8010, "Ticket": "1d0dDTr3pV7yq+vJRXD0UwuXAswH2YKH"}, "Message": null, "Result": "8j3ilF9xARTz/o//J0UU1jCo9AkF4sZg", "Success": true}
        console.log("generateLongToken1:", res.Context.Ticket)
        console.log("generateLongToken2:", res.Result)

        await UserManager.setLongTicket(res.Result)

        // that.props.navigation.replace("TabPage");
        that.props.navigation.replace("RFIDPage");

        this.closeLoading()


        // that.props.navigation.replace("TabPage");
        // that.props.navigation.replace("TabPage");
      }).catch((error)=>{
        // ToastUtils.showToast( error);
        Toast.info(error)
        this.closeLoading()
      });
    }

    
    closeUpdateDialog(){
      const that = this
      
      this.setState({isShowUpdate: false})
    }



 settingClick(){
  console.log('click setting')
  //  this.forceUpdate()
    this.setState({sVisible: true})
    // this.forceUpdate()
  

}





    render(){

      const footerButtons = [
        { 
          text: '取消', 
          onPress: () => {
            console.log('取消click')
              console.log(this.state.ipAddress)
              this.setState({sVisible: false})
              this.getDefaultData()
          } 
        },
        {
          text: '设置', 
          onPress: async () => {
            console.log( this.state.ipAddress) 
           

            if(this.state.ipAddress != null && this.state.ipAddress != '' && this.state.port != '' && this.state.port != null){

                Constants.serverPort = this.state.port
                Constants.serverUrl = this.state.ipAddress
                await UserManager.setIpAddress(this.state.ipAddress)
                await UserManager.setPort(this.state.port)
                this.setState({sVisible: false})
                console.log(Constants.serverUrl + ":" + Constants.serverPort)
              
            }else{
              Toast.info("服务器地址和端口不能为空")
            }
          }
        },
      ];

        return (
            <View style={styles.container}>

           
   
                 
            <ImageBackground source={require('../resource/images/bg.png') }
                         style={styles.ImageBgStyle}
                         resizeMode={'cover'} >

                              <View style={styles.settingBgView}>
                                  <TouchableOpacity activeOpacity={0.5} onPress={() => this.settingClick()}>
                                    <View style={styles.settingBtnBgStyle}>
                                        <Text style = {{color:"#0081cc"}}>设置</Text>
                  
                                    </View>
                                </TouchableOpacity>

                              </View>
                             {/* logo图片 */}
                             <View style = {styles.logoBg}>
                                 <Image style = {{width:157, height: 44}} source={require("../resource/images/login_logo.png")}></Image>
                             </View>
                              {/* email */}
                             <View style={styles.inputBg}>
                             <TextInput
                                 style={styles.inputStyle}
                                 placeholder='请输入账号'
                                 placeholderTextColor={"#B1B1B2"}
                                 onChangeText={(text) => {
                                    this.setState({username: text})
                                  }}
                                 value= {this.state.username}
                                 maxLength={40}
                                 defaultValue=""
                             />
             
                             </View>
             
                              {/* password */}
                              <View style={styles.inputBg}>
                             <TextInput
                                 placeholder="请输入密码"
                                 secureTextEntry={true}
                                 style={styles.inputStyle}
                                 maxLength={40}
                                 onChangeText={(text) => {
                                    this.setState({password: text})
                                  }}
                                 keyboardType={"default"}
                             />
             
                             </View>
             
                              {/* Login Btn */}
                              <TouchableOpacity activeOpacity={0.5} onPress={() => this.login()}>
                              <View style={styles.loginBtnBgStyle}>
                                     <Text style = {{color:"#ffffff"}}>登录</Text>
             
                             </View>
             
                             </TouchableOpacity>
             
                         {/* <View  style = {styles.registBtnStyle}>
                         <Text style = {{color:"#0081cc"}}>Regist</Text>
                         </View>
                          */}


                          
<AntdModal
                      title="设置"
                      key={111}
                      transparent={true}
                      maskClosable={false}
                      visible={this.state.sVisible}
                      footer={footerButtons}
                      animationType='slide'
                      popup={true}
                      
                      
                    >
                      <View style={{ paddingVertical: 20 }}>
                        <View style={styles.settingInputBg}>
                             <InputItem
                                 style={styles.settingInputStyle}
                                 placeholder='请输入服务器地址'
                                 placeholderTextColor={"#B1B1B2"}
                                 onChange={(text) => {
                                  this.setState({ipAddress: text})
                                 }}
                                 value= {this.state.ipAddress}
                                 maxLength={40}
                                 defaultValue=""
                                 editable={true}
                                 disabled={false}

                                 clear={true}
                             />
             
                             </View>
                             <View style={styles.settingInputBg}>
                             <InputItem
                                 style={styles.settingInputStyle}
                                 placeholder='请输入端口号'
                                 placeholderTextColor={"#B1B1B2"}
                                 onChange={(text) => {
                                  this.setState({port: text})
                                 }}
                                 value= {this.state.port}
                                 maxLength={40}
                                 defaultValue=""
                                 editable={true}
                                 disabled={false}

                                 clear={true}
                             />
             
                             </View>
                      </View>
                    </AntdModal>
             
                         </ImageBackground>


                         


                          {/* {
              this.state.isShowUpdate ? <UpdateVersionView  title={'版本更新'} content={this.state.updateMsg} isForce={this.state.isForce} skipClick={() => { 
                this.closeUpdateDialog()
              }} updateClick={()=>{

                console.log("apk url:", this.state.updateUrl)

                if(Platform.OS.toUpperCase() === "ANDROID"){
                  // upgrade(this.state.updateUrl);
                  this.downloadApk(this.state.updateUrl,()=>{

                  },)
                }

              }}/> : null
            }  */}
         


         
             
                      
             
                     </View>
             

        );
    }
}

const styles = StyleSheet.create({

    container:{
        flex: 1, 
        alignItems: 'center',
        justifyContent: 'center'
    },
    ImageBgStyle:{
        width: "100%",
        height:"100%",
        justifyContent:'flex-start',
        alignItems:'center'
        
    },

    settingBgView:{
     
      flexDirection:'row-reverse',
      alignItems: 'center',
      justifyContent:'space-between',
      height: px2dp(50),
      width: px2dp(375),

    },
    settingBtnBgStyle:{
      height: px2dp(50),
      width: px2dp(80),
      justifyContent:'center',
      alignItems:'center'
    },
    
    logoBg:{
        height: px2dp(50),
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'transparent',
        marginTop:px2dp(100)
    },

    inputBg:{
        width:px2dp(250),
        marginTop:px2dp(20),
        height: px2dp(50),
        marginLeft:px2dp(51),
        marginRight:px2dp(51),
        borderColor:'#999',
        borderWidth:px2dp(1),
        borderRadius:px2dp(25),
    },
    inputStyle:{
        marginLeft:px2dp(10),
        height: px2dp(50), 
        padding: 0
    },
    loginBtnBgStyle:{
        flexDirection:'column',
        marginTop:px2dp(50),
        marginLeft:px2dp(50),
        marginRight:px2dp(50),
        height: px2dp(50),
        width:px2dp(250),
        backgroundColor:"#0081cc",
        borderRadius: px2dp(25),
        alignItems: 'center',
        justifyContent: 'center'
        // 'space-between' | 'space-around' | 'space-evenly'

    },
    loginBtnStyle:{
        flex: 1,
        padding:0,
        margin:0
    },
    registBtnStyle:{
    
        height: px2dp(50),
        width:px2dp(250),
        borderColor:'#0081cc',
        borderWidth:px2dp(1),
        borderRadius:px2dp(25),
        backgroundColor:"white",
        position:'absolute',
        bottom: 20,
        justifyContent:"center",
        alignItems:"center"

    },
    settingInputBg:{
      
      marginTop:px2dp(10),
      height: px2dp(40),
      marginLeft:px2dp(10),
      marginRight:px2dp(10),
      borderColor:'#999',
      borderWidth:px2dp(1),
      borderRadius:px2dp(4),
     justifyContent:'center'
    },

    settingInputStyle:{
      marginLeft:px2dp(0),
      // height: px2dp(40), 
      padding: 0,
      fontSize: 14

  },
});
